import { 
  Project, 
  createProject as dbCreateProject,
  getAllProjects as dbGetAllProjects,
  getProjectById as dbGetProjectById,
  updateProject as dbUpdateProject,
  deleteProject as dbDeleteProject
} from '../database/index'
import path from 'path'
import { app } from 'electron'
import fs from 'fs'

// 项目文件夹路径
const projectsDir = path.join(app.getPath('userData'), 'projects')

// 确保项目目录存在
if (!fs.existsSync(projectsDir)) {
  fs.mkdirSync(projectsDir, { recursive: true })
}

/**
 * 项目服务
 * 处理项目的创建、查询、更新和删除
 */

/**
 * 创建新项目
 */
export async function createProject(projectData: {
  name: string
  description?: string
  resolution?: { width: number; height: number }
  frameRate?: number
}): Promise<Project> {
  return dbCreateProject({
    name: projectData.name,
    description: projectData.description
  })
}

/**
 * 获取所有项目
 */
export async function getAllProjects(): Promise<Project[]> {
  return dbGetAllProjects()
}

/**
 * 根据ID获取项目
 */
export async function getProjectById(id: number): Promise<Project | undefined> {
  return dbGetProjectById(id)
}

/**
 * 更新项目
 */
export async function updateProject(id: number, data: Partial<Project>): Promise<boolean> {
  return dbUpdateProject(id, data)
}

/**
 * 删除项目
 */
export async function deleteProject(id: number): Promise<boolean> {
  return dbDeleteProject(id)
}

// 以下是旧API的兼容层，将在后续版本中移除
// 这些函数已被弃用，请使用上面的新API

/**
 * 更新项目最后打开时间
 */
export async function updateProjectLastOpened(id: string): Promise<void> {
  const numericId = parseInt(id, 10)
  if (isNaN(numericId)) {
    throw new Error('Invalid project ID')
  }

  await updateProject(numericId, {
    lastOpenedAt: new Date()
  })
}

/**
 * @deprecated 使用 getAllProjects 代替
 */
export async function getRecentProjects(limit: number = 5): Promise<Project[]> {
  console.warn('getRecentProjects 已弃用，请使用 getAllProjects')
  const projects = await getAllProjects()
  return projects.slice(0, limit)
} 